﻿using System.Security.Claims;
using OpenIddict.Abstractions;
using static OpenIddict.Abstractions.OpenIddictConstants;

namespace WT.OpenIddict.Application.Manager;

public static class DestinationsUtils
{
    public static string[] GetClientCredentialsDestinations(Claim claim)
    {
        return claim.Type switch
        {
            // 当授予了 "profile" 范围时，允许 "name" 声明存储在访问令牌和身份令牌中
            Claims.Name when claim.Subject?.HasScope(Scopes.Profile) == true
                => [Destinations.AccessToken, Destinations.IdentityToken],

            // 其他情况默认仅存储在访问令牌中
            _ => [Destinations.AccessToken]
        };
    }

    public static string[] GetPasswordDestinations(Claim claim)
    {
        var destinations = new List<string>();

        switch (claim.Type)
        {
            case Claims.Name or Claims.PreferredUsername:
                destinations.Add(Destinations.AccessToken);
                if (claim.Subject?.HasScope(Scopes.Profile) == true)
                    destinations.Add(Destinations.IdentityToken);
                break;

            case Claims.Email:
                destinations.Add(Destinations.AccessToken);
                if (claim.Subject?.HasScope(Scopes.Email) == true)
                    destinations.Add(Destinations.IdentityToken);
                break;

            case Claims.Role:
                destinations.Add(Destinations.AccessToken);
                if (claim.Subject?.HasScope(Scopes.Roles) == true)
                    destinations.Add(Destinations.IdentityToken);
                break;

            case "AspNet.Identity.SecurityStamp":
                break; // 不添加任何内容

            default:
                destinations.Add(Destinations.AccessToken);
                break;
        }

        return destinations.ToArray();
    }
}